package com.bobo.encryption.symmetric;


import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

import sun.misc.BASE64Encoder;

/**
 * Java实现对称加密 （DES）
 * 加密级别 DES<3DES<AES<PBE
 * @author win7
 *
 */
public class DEStest {

	public static String bobo="www.bobo.com";
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
          JdkDES();
	}

	
	public static void JdkDES(){
		try {
		//1.初始化key秘钥	
			KeyGenerator keyGenerator=KeyGenerator.getInstance("DES");
			keyGenerator.init(new SecureRandom());
			SecretKey secretkey=keyGenerator.generateKey();
			 //key秘钥转换
			DESKeySpec desKeySpec=new DESKeySpec(secretkey.getEncoded());
			SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance("DES");
			Key  converSecreKey= secretKeyFactory.generateSecret(desKeySpec);
			
	   //2.加密		
			Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, converSecreKey);
			byte[] result= cipher.doFinal(bobo.getBytes());
			System.out.println("jdk des 加密:"+new BASE64Encoder().encode(result));//转成base64编码
			System.out.println("jdk des 加密:"+HexBin.encode(result)); //转成10进制编码
		
	   //3.解密
			cipher.init(Cipher.DECRYPT_MODE, converSecreKey);
			result= cipher.doFinal(result);
			System.out.println("jdk des 解密："+new String(result));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
